<link href="{$site_public}tpl/cms/avatar/cropper.css" rel="stylesheet">
<script src="{$site_public}tpl/cms/avatar/cropper.js"></script>
<link href="{$site_public}tpl/cms/avatar/avatar.css" rel="stylesheet">
<div class="modal fade zanpian-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display:none;">
  <div class="modal-dialog clearfix">
    <div class="modal-content clearfix">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
         <div class="zanpian-modal-tabs">
          <ul id="myTab pull-left">
          <li class="active">头像上传<li>
          </ul>
         </div>
    </div>

<div class="form-group">
<form class="form-horizontal" id="form-avatar" method="post" role="form"  action="{:zanpian_user_url('user/center/avatar')}" enctype="multipart/form-data" onSubmit="return false;">
<div class="avatar-body col-md-12">
<div class="avatar-upload">
<label for="avatarInput">头像上传</label>
<label class="avatar-input btn btn-primary" for="inputImage" style="float:left">
<input type="file" class="sr-only" id="inputImage" name="image" accept="image/*">请选择图片</label>
<input name="x" type="hidden">
<input name="y" type="hidden">
<input name="w" type="hidden">
<input name="h" type="hidden">
</div>
    <div class="row">
      <div class="col-md-9 col-sm-6 col-xs-5">
        <div class="avatar-view">
            <img id="avatar-image" src="{$site_public}tpl/cms/avatar/444.jpg">
        </div>
      </div>
      <div class="col-md-3 col-sm-6 col-xs-5" id="preview">
       <div class="avatar-preview avatar-preview-lg"></div>
       <div class="avatar-preview avatar-preview-md"></div>
       <div class="avatar-preview avatar-preview-sm" style="float:right"></div>
      </div>
    </div>
<div class="row avatar-tool">
<div class="col-md-9 col-sm-6 col-xs-5">
<div class="btn-group">
<button class="btn btn-primary fa fa-repeat" data-method="rotate" data-option="-45" type="button">右旋</button>
<button class="btn btn-primary fa fa-repeat" data-method="rotate" data-option="90" type="button">右旋</button>
</div>
<div class="btn-group">
<button class="btn btn-primary fa fa-repeat" data-method="zoom" data-option="0.1" type="button"> 放大</button>
<button class="btn btn-primary fa fa-repeat" data-method="zoom" data-option="-0.1" type="button"> 缩小</button>
</div>
<div class="btn-group">
<button class="btn btn-primary fa fa-repeat" data-method="move" data-option="-10" data-second-option="0" type="button">左</button>
<button class="btn btn-primary fa fa-repeat" data-method="move" data-option="10" data-second-option="0"  type="button">右</button>
<button class="btn btn-primary fa fa-repeat" data-method="move" data-option="0" data-second-option="-10" type="button">上</button>
<button class="btn btn-primary fa fa-repeat" data-method="move" data-option="0" data-second-option="10" type="button">下</button>
</div>
<div class="btn-group">
<button class="btn btn-primary fa fa-repeat" data-method="scaleX" data-option="-1" type="button">左右</button>
<button class="btn btn-primary fa fa-repeat" data-method="scaleY" data-option="-1" type="button">上下</button>
</div>
</div>
 <div class="col-md-3 col-sm-6 col-xs-5" style="padding-left:0;">
 <button type="button" class="btn btn-success btn-block" id="submit-avatar">保存</button>
</div>  
</div>  
    </div>
</form>
</div>
</div>
</div>
</div>
<script type="text/javascript">
var console = window.console || { log: function () {} };
var $image = $("#avatar-image");
// 获取裁切时的四个框
var x = $("input[name=x]");
var y = $("input[name=y]");
var w = $("input[name=w]");
var h = $("input[name=h]");
//选择图片时预览图片 并 调用cropper插件
$("input[type=file]").change(function() {
	// 先消毁，清除一下插件，否则连续调用插件时会失败
	$image.cropper("destroy");
	// this.files[0]：获取当前图片并转成URL地址
	var url = getObjectUrl(this.files[0]);
	console.log(url)
	$image.attr('src', url);// 设置url到预览图片上
	// 调出插件
	$image.cropper({
		// 裁切的框形状		   
		aspectRatio: 1/1,
		 // 显示预览的位置
		preview:'.avatar-preview',
		// 显示模式：图片不能无限缩小，但可以放大
		viewMode: 1,
		// 裁切时把参数保存到表单中
		crop: function(event) {
			x.val(event.detail.x);
			y.val(event.detail.y);
			w.val(event.detail.width);
			h.val(event.detail.height);
			w.val(event.detail.width);
		}
	});
});
// 预览时需要使用下面这个函数转换一下
function getObjectUrl(file) {
	var url = null;
	if (window.createObjectURL != undefined) {
		url = window.createObjectURL(file)
	} else if (window.URL != undefined) {
		url = window.URL.createObjectURL(file)
	} else if (window.webkitURL != undefined) {
		url = window.webkitURL.createObjectURL(file)
	}
	return url
}
// Methods
$('.avatar-tool').on('click', '[data-method]', function() {
	var $this = $(this);
	var data = $this.data();
	var cropper = $image.data('cropper');
	var cropped;
	var $target;
	var result;
	if ($this.prop('disabled') || $this.hasClass('disabled')) {
		return;
	}
	if (cropper && data.method) {
		data = $.extend({}, data); // Clone a new one
		if (typeof data.target !== 'undefined') {
			$target = $(data.target);
			if (typeof data.option === 'undefined') {
				try {
					data.option = JSON.parse($target.val());
				} catch (e) {
					console.log(e.message);
				}
			}
		}
		cropped = cropper.cropped;
		switch (data.method) {
		case 'rotate':
			if (cropped) {
				$image.cropper('clear');
			}
			break;
		case 'getCroppedCanvas':
			if (uploadedImageType === 'image/jpeg') {
				if (!data.option) {
					data.option = {};
				}
				data.option.fillColor = '#fff';
			}
			break;
		}
		result = $image.cropper(data.method, data.option, data.secondOption);
		switch (data.method) {
		case 'rotate':
			if (cropped) {
				$image.cropper('crop');
			}
			break;
		case 'scaleX':
		case 'scaleY':
			$(this).data('option', -data.option);
			break;
		case 'getCroppedCanvas':
			if (result) {
				// Bootstrap's Modal
				$('#getCroppedCanvasModal').modal().find('.modal-body').html(result);

				if (!$download.hasClass('disabled')) {
					download.download = uploadedImageName;
					$download.attr('href', result.toDataURL(uploadedImageType));
				}
			}
			break;
		case 'destroy':
			if (uploadedImageURL) {
				URL.revokeObjectURL(uploadedImageURL);
				uploadedImageURL = '';
				$image.attr('src', originalImageURL);
			}
			break;
		}
		if ($.isPlainObject(result) && $target) {
			try {
				$target.val(JSON.stringify(result));
			} catch (e) {
				console.log(e.message);
			}
		}
	}
});
$("#submit-avatar").click(function(e) {
	var $imgData = $image.cropper('getCroppedCanvas');
	var dataurl = $imgData.toDataURL('image/jpg');
	var blob = dataURLtoBlob(dataurl);
	var form = document.querySelector("#form-avatar");
	var formData = new FormData(form);
	formData.append("file", blob);
	$.showfloatdiv({
		txt: '头像上传中...',
		cssname: 'loading'
	});
	$.ajax({
		url: '{:zanpian_user_url('user/center/avatar')}',
		type: 'post',
		dataType: 'json',
		data: formData,
		cache: false,
		processData: false,
		contentType: false,
		success: function(r) {
			$.hidediv(r);
			if (parseInt(r.code) > 0) {
				$(".img-circle").attr("src",r.data+'?'+ Math.random());
				   setTimeout(function() {
				      $(".modal-dialog .close").trigger('click');
				   }, 500);
			}
		},
		error: function(r) {
			$.hidediv(r);
		},
	});
	return false;
});
//将base64格式图片转换为文件形式
function dataURLtoBlob(dataurl) {
	var arr = dataurl.split(','),
		mime = arr[0].match(/:(.*?);/)[1],
		bstr = atob(arr[1]),
		n = bstr.length,
		u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new Blob([u8arr], {
		type: mime
	});
}
$("input[type=file]").click(function() {
	$(".avatar-view").height($('#preview').height()-20);							
});	
$(function (){			
	$(window).resize(function() {
       $(".avatar-view").height($('#preview').height()-20);
    });
});			
</script>